package es.wandererteam.tapakitty;

import java.io.IOException;
import java.math.BigInteger;

import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.particle.SpriteParticleSystem;
import org.andengine.entity.particle.emitter.PointParticleEmitter;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.scene.menu.item.decorator.ScaleMenuItemDecorator;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.AnimatedSprite.IAnimationListener;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.TouchEvent;

import android.os.IBinder.DeathRecipient;
import android.util.Log;
import android.widget.Toast;
import es.wandererteam.tapakitty.bussines.FirstTestCat;
import es.wandererteam.tapakitty.bussines.GameStatus;
import es.wandererteam.tapakitty.bussines.ITouchCat;
import es.wandererteam.tapakitty.management.BaseScene;
import es.wandererteam.tapakitty.management.ResourcesManager;
import es.wandererteam.tapakitty.management.SceneManager;
import es.wandererteam.tapakitty.management.SceneManager.SceneType;
public class GameScene extends BaseScene implements IOnSceneTouchListener,
		IOnMenuItemClickListener, ITouchCat {

	// ===========================================================
	// Constants
	// ===========================================================
	protected static int CAMERA_WIDTH = 480;
	protected static int CAMERA_HEIGHT = 320;
	
	// ---------------------------------------------
	// VARIABLES
	// ---------------------------------------------
	private boolean onanimate = false;
	private long count01 = 0;
	private long count02 = 0;
	private long nyanspersec = 1000;

	// ---------------------------------------------
	// VISUAL VARIABLES
	// ---------------------------------------------
	private final int STATS_BUTTON = 0;
	private final int SHOP_BUTTON = 1;
	MenuScene menuScene;
	Sound yourSound;
	Sprite backgroundWindowSprite;
	FirstTestCat cat;
	Text numberText;
	Text helloText;
	
	private AnimatedSprite[] animatedSpriteArray= new AnimatedSprite[20];
	private int indexPlusOne=0;
	private AnimatedSprite sprplusone;
	private AnimatedSprite layertextanimated;

	private PointParticleEmitter particleEmitter;
	private SpriteParticleSystem particleSystem;

	@Override
	public void createScene() {
		

		CAMERA_WIDTH = resourcesManager.getInstance().SCREEN_WIDTH;
		CAMERA_HEIGHT = resourcesManager.getInstance().SCREEN_HEIGHT;
		this.camera.set(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		
		
		// resourcesManager.loadGameAudio();
		setOnSceneTouchListener(this);
		// registerTouchArea(key0);

		createBackground();
		createButtons();
		createCat();
		createCounter();
		setUpdate();
		// createHello();
		// nextText();

	}

	@Override
	public void onBackKeyPressed() {
		// SceneManager.getInstance().loadMenuScene(engine);
		this.disposeScene();
		System.exit(0);
	}

	@Override
	public SceneType getSceneType() {
		return SceneType.SCENE_GAME;
	}

	@Override
	public void disposeScene() {
		camera.setChaseEntity(null);
	}

	public void completeWindow() {

	}

	public void loadSounds() {
		try {
			yourSound = SoundFactory.createSoundFromAsset(
					engine.getSoundManager(), activity, "PresssO.ogg");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void createHello() {

		layertextanimated = new AnimatedSprite(10,
				resourcesManager.SCREEN_HEIGHT / 4, resourcesManager.layertext,
				this.vbom) {
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				detachChild(layertextanimated);
				return true;
			}
		};
		attachChild(layertextanimated);

		layertextanimated.animate(250, true, new IAnimationListener() {

			@Override
			public void onAnimationStarted(AnimatedSprite pAnimatedSprite,
					int pInitialLoopCount) {
				onanimate = true;
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationFrameChanged(AnimatedSprite pAnimatedSprite,
					int pOldFrameIndex, int pNewFrameIndex) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationLoopFinished(AnimatedSprite pAnimatedSprite,
					int pRemainingLoopCount, int pInitialLoopCount) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationFinished(AnimatedSprite pAnimatedSprite) {
				// TODO Auto-generated method stub

			}

		});
	}

	private void nextText() {
		helloText = new Text(10, 0, resourcesManager.numberFont, "Hellouser",
				9, resourcesManager.vbom);
		numberText.setText("Hellouser");
		attachChild(numberText);
	}

	private void setUpdate() {
		this.registerUpdateHandler(new IUpdateHandler() {
			@Override
			public void onUpdate(float pSecondsElapsed) {
				count02 = count02 - count01;
				if (count02 >= nyanspersec) {
					count01 = System.currentTimeMillis();
					GameStatus.CurrentNyansNumber = GameStatus.CurrentNyansNumber.add(BigInteger
							.valueOf((int)GameStatus.NYANS_PER_SECOND));
					numberText.setText(GameStatus.CurrentNyansNumber.toString());
				} else {
					count02 = System.currentTimeMillis();
				}
			}

			@Override
			public void reset() {
				// TODO Auto-generated method stub

			}
		});
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub
		TouchCat(pSceneTouchEvent, 1);
		return false;
	}

	@Override
	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {
		switch (pMenuItem.getID()) {
		case STATS_BUTTON:
			SceneManager.getInstance().loadObjectScene(engine);
			return true;
		case SHOP_BUTTON:
			SceneManager.getInstance().loadShopScene(engine);
			return true;
		default:
			return false;
		}
	}

	// ---------------------------------------------
	// GAME METHODS
	// ---------------------------------------------

	private void createCat() {
		/*
		 * int pXCat = (int) (resourcesManager.SCREEN_WIDTH / 2 -
		 * resourcesManager.catTiledTextureRegion .getWidth() / 2); int pYCat =
		 * (int) (7 * resourcesManager.SCREEN_HEIGHT / 8 -
		 * resourcesManager.catTiledTextureRegion .getHeight()); cat = new
		 * TiledSprite(pXCat, pYCat, resourcesManager.catTiledTextureRegion,
		 * vbom) {
		 * 
		 * @Override public boolean onAreaTouched(final TouchEvent
		 * pSceneTouchEvent, final float pTouchAreaLocalX, final float
		 * pTouchAreaLocalY) {
		 * 
		 * catTouched(pSceneTouchEvent, 0);
		 * 
		 * return true; } };
		 */

		// FirstTestCat cat = new FirstTestCat(this);
		cat = new FirstTestCat(this);

		registerTouchArea(cat.getSpriteTexture());
		attachChild(cat.getSpriteTexture());

	}

	private void createButtons() {
		menuScene = new MenuScene(camera);
		menuScene.setPosition(0, 0);

		final IMenuItem statsMenuItem = new ScaleMenuItemDecorator(
				new SpriteMenuItem(STATS_BUTTON,
						resourcesManager.pawTextureRegion, vbom), 1.2f, 1);

		final IMenuItem shopMenuItem = new ScaleMenuItemDecorator(
				new SpriteMenuItem(SHOP_BUTTON,
						resourcesManager.bellTextureRegion, vbom) {
				}, 1.2f, 1);

		menuScene.addMenuItem(statsMenuItem);
		menuScene.addMenuItem(shopMenuItem);

		menuScene.buildAnimations();
		menuScene.setBackgroundEnabled(false);

		statsMenuItem.setPosition(
				resourcesManager.SCREEN_WIDTH - statsMenuItem.getWidth(),
				resourcesManager.SCREEN_HEIGHT - statsMenuItem.getHeight());
		shopMenuItem.setPosition(0, resourcesManager.SCREEN_HEIGHT
				- statsMenuItem.getHeight());
		menuScene.setOnMenuItemClickListener(this);

		setChildScene(menuScene);
	}

	private void createCounter() {
		numberText = new Text(10, 0, resourcesManager.numberFont, "0123456789",
				10, resourcesManager.vbom);
		numberText.setText("0");
		attachChild(numberText);
	}

	private void createBackground() {
		backgroundWindowSprite = new Sprite(0, 0,
				resourcesManager.windowBackgroundTextureRegion,
				resourcesManager.vbom);
		attachChild(backgroundWindowSprite);
	}

	@Override
	public void TouchCat(TouchEvent pSceneTouchEvent, int from) {
		if (pSceneTouchEvent.isActionDown() && from == 0) {
			// cat.setCurrentTileIndex(1);
			cat.getSpriteTexture().setCurrentTileIndex(1);
			double p = Math.random();
			// resourcesManager.activity.toastOnUIThread("Random: " +
			// p,Toast.LENGTH_SHORT);
			if (p <= cat.getRibbonAccessoryLeft().MIAU_PROBABILITY)
				resourcesManager.catTouchSound.play();
			GameStatus.CurrentNyansNumber = GameStatus.CurrentNyansNumber.add(new BigInteger("1"));
			numberText.setText(GameStatus.CurrentNyansNumber.toString());

		//	if (onanimate == false)
				animationPlusOne(pSceneTouchEvent.getX(),pSceneTouchEvent.getY());

		}

		if (pSceneTouchEvent.isActionUp()) {
			cat.getSpriteTexture().setCurrentTileIndex(0);
		}
		// cat.setCurrentTileIndex(0);

	}
	double rest=0;
private void animateIndex( int indexPlusOne, float X, float Y){
	animatedSpriteArray[indexPlusOne]=new AnimatedSprite(X, Y, resourcesManager.regplusone,this.vbom);
	animatedSpriteArray[indexPlusOne].setPosition(X - animatedSpriteArray[indexPlusOne].getWidth() / 2, Y- resourcesManager.regplusone.getHeight());
	attachChild(animatedSpriteArray[indexPlusOne]);
	rest=Math.random() * 5;
	animatedSpriteArray[indexPlusOne].setWidth((float) (animatedSpriteArray[indexPlusOne].getWidth()-rest));
	animatedSpriteArray[indexPlusOne].setHeight((float) (animatedSpriteArray[indexPlusOne].getHeight()-rest));
	System.out.println("indexPlusOne_ANIMATED"+indexPlusOne);
	animatedSpriteArray[indexPlusOne].animate(30,false, new IAnimationListener(){

		@Override
		public void onAnimationStarted(AnimatedSprite pAnimatedSprite,
				int pInitialLoopCount) {
			//onanimate = true;
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimationFrameChanged(AnimatedSprite pAnimatedSprite,
				int pOldFrameIndex, int pNewFrameIndex) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimationLoopFinished(AnimatedSprite pAnimatedSprite,
				int pRemainingLoopCount, int pInitialLoopCount) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimationFinished(AnimatedSprite pAnimatedSprite) {
			// TODO Auto-generated method stub
			deTach();
			//onanimate = false;
		}
	});
}
private void deTach(){
	detachChild(animatedSpriteArray[indexPlusOne]);
	indexPlusOne++;
}
	public void animationPlusOne(float X, float Y) {
		System.out.println("indexPlusOne_COMPARED"+indexPlusOne);
		if(indexPlusOne<20)animateIndex(indexPlusOne,X,Y);
		else {indexPlusOne=0;animateIndex(indexPlusOne,X,Y);}
		/*
		sprplusone = new AnimatedSprite(X, Y, resourcesManager.regplusone,
				this.vbom);
		sprplusone.setPosition(X - sprplusone.getWidth() / 2, Y
				- resourcesManager.regplusone.getHeight());
	
		attachChild(sprplusone);
		sprplusone.animate(30, false, new IAnimationListener() {

			@Override
			public void onAnimationStarted(AnimatedSprite pAnimatedSprite,
					int pInitialLoopCount) {
				onanimate = true;
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationFrameChanged(AnimatedSprite pAnimatedSprite,
					int pOldFrameIndex, int pNewFrameIndex) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationLoopFinished(AnimatedSprite pAnimatedSprite,
					int pRemainingLoopCount, int pInitialLoopCount) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationFinished(AnimatedSprite pAnimatedSprite) {
				// TODO Auto-generated method stub
				detachChild(sprplusone);
				onanimate = false;

			}

		});
*/
	}

}
